package com.yoouce.patchmng.controller;

import com.yoouce.patchmng.bean.UserInfo;
import com.yoouce.patchmng.init.SystemContants;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *
 * Action层超类 1：JSon数据的封装 2：分页组件
 *
 * @author Scott.Lee
 * @version [版本号, 2015年9月16日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */

public class BaseController
{
    protected static final Logger LOG = Logger.getLogger(BaseController.class);
    
    protected HttpServletRequest request;
    
    protected HttpServletResponse response;
    
    protected HttpSession session;
    
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request,
            HttpServletResponse response)
    {
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }
    
    public HttpServletRequest getRequest()
    {
        return request;
    }
    
    public HttpServletResponse getResponse()
    {
        return response;
    }
    
    public HttpSession getSession()
    {
        return session;
    }
    
    /**
     * 获取session用户信息
     **/
    public UserInfo getSessinUser()
    {
        return (UserInfo) this.getSession()
                .getAttribute(SystemContants.USER_KEY);
    }
    
    /**
     *
     * @param obj
     */
    public void outJson(Object obj)
    {
        outJsonString(JSONObject.fromObject(obj).toString());
    }
    
    public void outJsonArray(Object array)
    {
        outJsonString(JSONArray.fromObject(array).toString());
    }
    
    /**
     *
     * @param str
     */
    private void outJsonString(String str)
    {
        response.setContentType("text/javascript;charset=UTF-8");
        outString(str);
    }
    
    /**
     *
     * @param str
     */
    private void outString(String str)
    {
        try
        {
            PrintWriter out = response.getWriter();
            out.write(str);
            LOG.debug(str);
        }
        catch (IOException e)
        {
            LOG.info(e);
        }
    }

    public String getRealPath(String path)
    {
       return request.getSession().getServletContext().getRealPath(path);
    }
}
